//
//  VideoAboutViewController.m
//  iOS-Learning-Demo
//
//  Created by yuan xiaodong on 2021/12/24.
//  Copyright © 2021 yuan. All rights reserved.
//

#import "VideoAboutViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "DolpVideoCompressTool.h"
#import "DolpProgressView.h"

#define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
#define TOCK NSLog(@"代码执行时间 >>> Time: %f", CFAbsoluteTimeGetCurrent() - start);

@interface VideoAboutViewController ()

@property (nonatomic, strong) UIButton *confirmBtn;

@property (nonatomic, strong) DolpVideoCompressTool *encoder;

@property (nonatomic, strong) DolpProgressView *progressView;

@end

@implementation VideoAboutViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"视频相关";
    self.view.backgroundColor = UIColor_F8;
    
    UIButton *btn = UIButton.new;
    btn.backgroundColor = UIColorFromRGB(0x9B9B9B);
    [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    [btn setTitle:@"开始压缩" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(startCompress) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.cornerRadius  = 6;
    btn.layer.masksToBounds = YES;
    btn.frame = CGRectMake(100, 100, 100, 50);
    
    UIButton *endBtn = UIButton.new;
    endBtn.backgroundColor = UIColorFromRGB(0x9B9B9B);
    [endBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    [endBtn setTitle:@"取消压缩" forState:UIControlStateNormal];
    [endBtn addTarget:self action:@selector(endCompress) forControlEvents:UIControlEventTouchUpInside];
    endBtn.frame = CGRectMake(btn.left, btn.bottom+20, btn.width, btn.height);
    
    self.progressView.frame = CGRectMake(0, endBtn.bottom + 20, 50, 50);
    self.progressView.centerX = endBtn.centerX;
    [self.view addSubview:self.progressView];
    
    [self.view addSubview:btn];
    [self.view addSubview:endBtn];
}

- (DolpProgressView *)progressView {
    if (_progressView == nil) {
        _progressView = [[DolpProgressView alloc] init];
    }
    return _progressView;
}

- (void)testCycleProgress{
    //进度条
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.progressView.progress = .3;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.progress = .5;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.progress = .8;
            });
            
        });
        
    });
}

- (void)startCompress{

    NSString *originalPath = [[NSBundle mainBundle] pathForResource:@"big720" ofType:@"mp4"];
    NSURL *originalUrl = [NSURL fileURLWithPath:originalPath];
    
    NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    savePath = [NSString stringWithFormat:@"%@/video.MP4",savePath];
    NSURL *saveUrl = [NSURL fileURLWithPath:savePath];
    
    TICK
    [self compressVideoUrl:originalUrl
                 outputUrl:saveUrl
                  isOrigin:YES
           completionBlock:^(DolpVideoCompressTool * _Nonnull videoTool) {
        
        TOCK
        
        switch (videoTool.status) {
            case AVAssetExportSessionStatusCompleted: {
                NSLog(@"Video export succeeded");
                NSData *fileData = [NSData dataWithContentsOfURL:saveUrl];
                NSInteger fileSize = fileData.length;
                NSLog(@"压缩后大小：%@",[self formatFileSize:fileSize]);
                break;
            }
            case AVAssetExportSessionStatusCancelled: {
                NSLog(@"Video export cancelled");
                break;
            }
            default: {
                NSLog(@"Video export failed with error: %@ (%li)", self.encoder.error.localizedDescription, self.encoder.error.code);
                break;
            }
        }
    } progress:^(CGFloat progress) {
        NSLog(@"progress: %f", progress);
        dispatch_async(dispatch_get_main_queue(), ^{
            self.progressView.progress = progress;
        });
        
    }];
}

- (void)endCompress{
    if (self.encoder){
        NSLog(@"压缩取消");
        [self.encoder cancelExport];
    }
}

- (void)compressVideoUrl:(NSURL *)videoOriginUrl
               outputUrl:(NSURL *)outputURL
                isOrigin:(BOOL)isOrigin
         completionBlock:(DolpVideoCompressBlock _Nonnull)completionBlock
                progress:(DolpVideoCompressProgressBlock _Nullable)progressBlock {
    
    NSData *fileData = [NSData dataWithContentsOfURL:videoOriginUrl];
    NSInteger fileSize = fileData.length;
    NSLog(@"原始大小：%@",[self formatFileSize:fileSize]);
    NSLog(@"输出路径：%@",outputURL);
    
    // 删除目标地址
    NSError *error;
    [[NSFileManager defaultManager] removeItemAtPath:outputURL.path error:&error];
    
    // 初始化 encoder
    self.encoder = [DolpVideoCompressTool.alloc initWithAsset:[AVAsset assetWithURL:videoOriginUrl]];
    self.encoder.outputFileType  = AVFileTypeMPEG4;
    self.encoder.outputURL       = outputURL;
    
    // 获取压缩视频Size
    // 分辨率：原图720*1280，非原图540*960
    // 帧率：30
    CGSize prioritySize = CGSizeMake(540, 960);
    CGSize originSize   = [DolpVideoCompressTool sizeVideoUrl:videoOriginUrl];
    if (isOrigin){
        if (originSize.width > originSize.height){
            prioritySize = CGSizeMake(1280, 720);
        }else{
            prioritySize = CGSizeMake(720, 1280);
        }
    }else{
        if (originSize.width > originSize.height){
            prioritySize = CGSizeMake(960, 540);
        }else{
            prioritySize = CGSizeMake(540, 960);
        }
    }
    
    NSLog(@"原始大小：%@",NSStringFromCGSize(originSize));
    NSLog(@"目标大小：%@",NSStringFromCGSize(prioritySize));
    
    CGSize targetSize   = [DolpVideoCompressTool sizeFrom:originSize toSize:prioritySize];
    
    // 设置压缩配置
    self.encoder.videoSettings = [DolpVideoCompressTool dicVideoSettingsSize:targetSize bitRate:0];
    self.encoder.audioSettings = [DolpVideoCompressTool dicAudioSettings];
    // 异步压缩
    [self.encoder compressCompletion:completionBlock progress:progressBlock];
}

- (NSString *)formatFileSize:(unsigned long long)size {
    NSString *formattedStr = nil;
    if (size == 0) {
        formattedStr = @"0B";
    } else if (size > 0 && size < 1024) {
        formattedStr = [NSString stringWithFormat:@"%quB", size];
    } else if (size >= 1024 && size < pow(1024, 2)) {
        formattedStr = [NSString stringWithFormat:@"%.2fK", (size / 1024.)];
    } else if (size >= pow(1024, 2) && size < pow(1024, 3)) {
        formattedStr = [NSString stringWithFormat:@"%.2fM", (size / pow(1024, 2))];
    } else if (size >= pow(1024, 3) && size < pow(1024, 4)) {
        formattedStr = [NSString stringWithFormat:@"%.2fG", (size / pow(1024, 3))];
    } else if (size >= pow(1024, 4)) {
        formattedStr = [NSString stringWithFormat:@"%.2fT", (size / pow(1024, 4))];
    }
    return formattedStr;
}

@end
